/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package kimo.persistence.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import kimo.persistence.entities.Prefecture;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import kimo.persistence.controllers.exceptions.IllegalOrphanException;
import kimo.persistence.controllers.exceptions.NonexistentEntityException;
import kimo.persistence.controllers.exceptions.PreexistingEntityException;
import kimo.persistence.entities.Region;

/**
 *
 * @author a381u296
 */
public class RegionJpaController implements Serializable {

    public RegionJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Region region) throws PreexistingEntityException, Exception {
        if (region.getPrefectureList() == null) {
            region.setPrefectureList(new ArrayList<Prefecture>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Prefecture> attachedPrefectureList = new ArrayList<Prefecture>();
            for (Prefecture prefectureListPrefectureToAttach : region.getPrefectureList()) {
                prefectureListPrefectureToAttach = em.getReference(prefectureListPrefectureToAttach.getClass(), prefectureListPrefectureToAttach.getPrefectureId());
                attachedPrefectureList.add(prefectureListPrefectureToAttach);
            }
            region.setPrefectureList(attachedPrefectureList);
            em.persist(region);
            for (Prefecture prefectureListPrefecture : region.getPrefectureList()) {
                Region oldPrefectureRegionIdOfPrefectureListPrefecture = prefectureListPrefecture.getPrefectureRegionId();
                prefectureListPrefecture.setPrefectureRegionId(region);
                prefectureListPrefecture = em.merge(prefectureListPrefecture);
                if (oldPrefectureRegionIdOfPrefectureListPrefecture != null) {
                    oldPrefectureRegionIdOfPrefectureListPrefecture.getPrefectureList().remove(prefectureListPrefecture);
                    oldPrefectureRegionIdOfPrefectureListPrefecture = em.merge(oldPrefectureRegionIdOfPrefectureListPrefecture);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findRegion(region.getRegionId()) != null) {
                throw new PreexistingEntityException("Region " + region + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Region region) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Region persistentRegion = em.find(Region.class, region.getRegionId());
            List<Prefecture> prefectureListOld = persistentRegion.getPrefectureList();
            List<Prefecture> prefectureListNew = region.getPrefectureList();
            List<String> illegalOrphanMessages = null;
            for (Prefecture prefectureListOldPrefecture : prefectureListOld) {
                if (!prefectureListNew.contains(prefectureListOldPrefecture)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Prefecture " + prefectureListOldPrefecture + " since its prefectureRegionId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Prefecture> attachedPrefectureListNew = new ArrayList<Prefecture>();
            for (Prefecture prefectureListNewPrefectureToAttach : prefectureListNew) {
                prefectureListNewPrefectureToAttach = em.getReference(prefectureListNewPrefectureToAttach.getClass(), prefectureListNewPrefectureToAttach.getPrefectureId());
                attachedPrefectureListNew.add(prefectureListNewPrefectureToAttach);
            }
            prefectureListNew = attachedPrefectureListNew;
            region.setPrefectureList(prefectureListNew);
            region = em.merge(region);
            for (Prefecture prefectureListNewPrefecture : prefectureListNew) {
                if (!prefectureListOld.contains(prefectureListNewPrefecture)) {
                    Region oldPrefectureRegionIdOfPrefectureListNewPrefecture = prefectureListNewPrefecture.getPrefectureRegionId();
                    prefectureListNewPrefecture.setPrefectureRegionId(region);
                    prefectureListNewPrefecture = em.merge(prefectureListNewPrefecture);
                    if (oldPrefectureRegionIdOfPrefectureListNewPrefecture != null && !oldPrefectureRegionIdOfPrefectureListNewPrefecture.equals(region)) {
                        oldPrefectureRegionIdOfPrefectureListNewPrefecture.getPrefectureList().remove(prefectureListNewPrefecture);
                        oldPrefectureRegionIdOfPrefectureListNewPrefecture = em.merge(oldPrefectureRegionIdOfPrefectureListNewPrefecture);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = region.getRegionId();
                if (findRegion(id) == null) {
                    throw new NonexistentEntityException("The region with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Region region;
            try {
                region = em.getReference(Region.class, id);
                region.getRegionId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The region with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Prefecture> prefectureListOrphanCheck = region.getPrefectureList();
            for (Prefecture prefectureListOrphanCheckPrefecture : prefectureListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Region (" + region + ") cannot be destroyed since the Prefecture " + prefectureListOrphanCheckPrefecture + " in its prefectureList field has a non-nullable prefectureRegionId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(region);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Region> findRegionEntities() {
        return findRegionEntities(true, -1, -1);
    }

    public List<Region> findRegionEntities(int maxResults, int firstResult) {
        return findRegionEntities(false, maxResults, firstResult);
    }

    private List<Region> findRegionEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Region.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Region findRegion(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Region.class, id);
        } finally {
            em.close();
        }
    }

    public int getRegionCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Region> rt = cq.from(Region.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
